from django.shortcuts import render
from django.http import HttpResponse
import json
from .models import *
import urllib
from datetime import date, datetime, timedelta
import urllib.request
import random
import time
from .utils import *
import pymysql
# Create your views here.


def user_login(request):
    code = request.GET["userCode"]
    user_name = request.GET["userName"]
    openid = get_openid(code)
    user = User.objects.filter(openid=openid)
    obj = dict()
    if len(user) == 0:
        now = datetime.now().__format__("%Y-%m-%d %H:%M:%S")
        user = User(openid=openid, username=user_name, reg_time=now, instruction=0, money=10000)
        user.save()
        obj["firstLogin"] = 1
        obj["money"] = 10000
        obj["haveInfo"] = 0

        preference_vector = PreferenceVector(openid)
        preference_vector.save()
        preference = Preference(openid)
        preference.save()
        funds = Fund.objects.filter()
        for fund in funds:
            user_fund_score = UserFundScore(user_id=openid, fund_id=fund.fund_id, is_operated=0, score=0)
            user_fund_score.save()
    else:
        user = User.objects.get(openid=openid)
        reminds = Remind.objects.filter(user_id=openid, see=0)
        have_info = 0
        firstLogin = 0
        if len(reminds) != 0:
            have_info = 1
        if user.instruction == 0:
            firstLogin = 1
        obj["firstLogin"] = firstLogin
        obj["money"] = user.money
        obj["haveInfo"] = have_info
        user.username = user_name
        user.image_url = request.GET["userImage"]
        user.save()
    return HttpResponse(json.dumps(obj))


def list(request):
    funds = []
    types = []
    sort_type = "0"
    if request.body:
        obj = json.loads(request.body)
        sort_type = obj["sortType"]
        if sort_type == "0":
            print("刚进入", time.time())
            now_fund = obj["list"]
            # popular(5)->score(10)->rand(5)
            # popular(5)
            all_click = FundClick.objects.all()
            tmp = []
            for click in all_click:
                tmp.append((click.fund_id, click.click_count))
            all_click = sorted(tmp, key=lambda fd: fd[1], reverse=True)
            cnt = 0
            for click in all_click:
                if click[0] not in now_fund:
                    now_fund.append(click[0])
                    funds.append(click[0])
                    types.append(0)
                    cnt += 1
                if cnt >= 5:
                    break
            have_login = obj['haveLogin']
            print("click更新完成", time.time())
            if have_login == 1:  # have logged in, include preference
                # score(5)
                user_id = get_openid(obj['userCode'])
                #all_score = UserFundScore.objects.filter(user_id=user_id)
                sql = "select * from api_userfundscore where user_id='%s'" % (user_id)
                db = pymysql.connect(host="114.115.160.16", user="root", password="123456Aa!", database="fund")
                cursor = db.cursor()
                cursor.execute(sql)
                all_score = cursor.fetchall()
                tmp = []
                for score in all_score:
                    tmp.append((score[2], score[4]))
                all_score = sorted(tmp, key=lambda sr: sr[1], reverse=True)
                cnt = 0
                for score in all_score:
                    if score[0] not in now_fund:
                        now_fund.append(score[0])
                        funds.append(score[0])
                        types.append(2)
                        cnt += 1
                    if cnt >= 5:
                        break
                # predict(5)
                #all_fund = High.objects.all()
                sql = "select * from api_high"
                db = pymysql.connect(host="114.115.160.16", user="root", password="123456Aa!", database="fund")
                cursor = db.cursor()
                cursor.execute(sql)
                all_fund = cursor.fetchall()
                for i in range(5):
                    tmp = random.choice(all_fund)[0]
                    while tmp in now_fund:
                        tmp = random.choice(all_fund)[0]
                    now_fund.append(tmp)
                    funds.append(tmp)
                    types.append(1)
                # random(5)
                #all_fund = Fund.objects.all()
                sql = "select * from api_fund"
                db = pymysql.connect(host="114.115.160.16", user="root", password="123456Aa!", database="fund")
                cursor = db.cursor()
                cursor.execute(sql)
                all_fund = cursor.fetchall()
                for i in range(5):
                    tmp = random.choice(all_fund)[0]
                    while tmp in now_fund:
                        tmp = random.choice(all_fund)[0]
                    now_fund.append(tmp)
                    funds.append(tmp)
                    types.append(3)
            else:  # not logged in
                # random(15)
                #all_fund = Fund.objects.all()
                sql = "select * from api_fund"
                db = pymysql.connect(host="114.115.160.16", user="root", password="123456Aa!", database="fund")
                cursor = db.cursor()
                cursor.execute(sql)
                all_fund = cursor.fetchall()
                for i in range(15):
                    tmp = random.choice(all_fund)[0]
                    while tmp in now_fund:
                        tmp = random.choice(all_fund)[0]
                    now_fund.append(tmp)
                    funds.append(tmp)
                    types.append(3)
            print("基金挑选完成", time.time())
        elif sort_type == "1":  # new day_growth 20
            page = len(obj["list"]) / 30 + 1
            tmp = get_rank('r', 30, page)
            fund_list = []
            for fund in tmp:
                d = dict()
                d["fundId"] = fund[0]
                d["name"] = fund[1]
                d["increase"] = fund[2]
                d["value"] = fund[3]
                d["type"] = 3
                fund_list.append(d)
            return HttpResponse(json.dumps({"data": fund_list}))
            now_fund = obj["list"]
            all_fund = Fund.objects.all()
            tmp = dict()
            for fund in all_fund:
                tmp[fund.fund_id] = fund.day_growth
            length = len(now_fund)
            cnt = 0
            for key, value in reversed(sorted(tmp.items(), key=lambda kv: (kv[1], kv[0]))):
                if length <= cnt <= length + 20:
                    funds.append(key)
                    types.append(3)
                if cnt > length + 20:
                    break
                cnt += 1
        elif sort_type == "2":  # new week_growth 20
            page = len(obj["list"]) / 30 + 1
            tmp = get_rank('z',30, page)
            fund_list = []
            for fund in tmp:
                d = dict()
                d["fundId"] = fund[0]
                d["name"] = fund[1]
                d["increase"] = fund[2]
                d["value"] = fund[3]
                d["type"] = 3
                fund_list.append(d)
            return HttpResponse(json.dumps({"data": fund_list}))

            now_fund = obj["list"]
            all_fund = Fund.objects.all()
            tmp = dict()
            for fund in all_fund:
                tmp[fund.fund_id] = fund.week_growth
            length = len(now_fund)
            cnt = 0
            for key, value in reversed(sorted(tmp.items(), key=lambda kv: (kv[1], kv[0]))):
                if length <= cnt <= length + 20:
                    funds.append(key)
                    types.append(3)
                if cnt > length + 20:
                    break
                cnt += 1

        elif sort_type == "3":  # new month_growth 20
            page = len(obj["list"]) / 30 + 1
            tmp = get_rank('1y', 30, page)
            fund_list = []
            for fund in tmp:
                d = dict()
                d["fundId"] = fund[0]
                d["name"] = fund[1]
                d["increase"] = fund[2]
                d["value"] = fund[3]
                d["type"] = 3
                fund_list.append(d)
            return HttpResponse(json.dumps({"data": fund_list}))

            now_fund = obj["list"]
            all_fund = Fund.objects.all()
            tmp = dict()
            for fund in all_fund:
                tmp[fund.fund_id] = fund.month_growth
            length = len(now_fund)
            cnt = 0
            for key, value in reversed(sorted(tmp.items(), key=lambda kv: (kv[1], kv[0]))):
                if length <= cnt <= length + 20:
                    funds.append(key)
                    types.append(3)
                if cnt > length + 20:
                    break
                cnt += 1

        else:  # new year_growth 20
            page = len(obj["list"]) / 30 + 1
            tmp = get_rank('jn', 30, page)
            fund_list = []
            for fund in tmp:
                d = dict()
                d["fundId"] = fund[0]
                d["name"] = fund[1]
                d["increase"] = fund[2]
                d["value"] = fund[3]
                fund_list.append(d)
            return HttpResponse(json.dumps({"data": fund_list}))

            now_fund = obj["list"]
            all_fund = Fund.objects.all()
            tmp = dict()
            for fund in all_fund:
                tmp[fund.fund_id] = fund.year_growth
            length = len(now_fund)
            cnt = 0
            for key, value in reversed(sorted(tmp.items(), key=lambda kv: (kv[1], kv[0]))):
                if length <= cnt <= length + 20:
                    funds.append(key)
                    types.append(3)
                if cnt > length + 20:
                    break
                cnt += 1



    # funds = Fund.objects.all()
    res = dict()
    funds_list = []
    cnt = 0
    print("开始查找信息", time.time())
    for fund_id in funds:
        '''
        fund = Fund.objects.get(fund_id=fund_id)
        value = get_price_by_id(fund.fund_id)
        if sort_type == "0" or sort_type == "1":
            increase = fund.day_growth
        elif sort_type == "2":
            increase = fund.week_growth
        elif sort_type == "3":
            increase = fund.month_growth
        else:
            increase = fund.year_growth
        obj = {
            'fundId': fund.fund_id,
            'name': fund.fund_name,
            'increase': increase,
            'value': value,
            'type': types[cnt]
        }
        '''
        obj = get_fund_info_by_id(fund_id, int(sort_type))
        obj["type"] = types[cnt]
        cnt += 1
        funds_list.append(obj)
    #print(funds)
    print("全完成", time.time())
    res["data"] = funds_list
    return HttpResponse(json.dumps(res))


def detail(request):
    fund_id = request.GET["fundId"]
    have_login = request.GET["haveLogin"]
    openid = 0
    have_follow = 0
    print("刚开始", time.time())
    # 有人查看基金详细信息，点击次数加一
    fund_click = FundClick.objects.get(fund_id=fund_id)
    fund_click.click_count = fund_click.click_count + 1
    fund_click.save()
    print("点击次数增加完成", time.time())
    if have_login == "1":
        openid = get_openid(request.GET["userCode"])
        follows = Follow.objects.filter(user_id=openid)
        for follow in follows:
            if follow.fund_id == fund_id:
                have_follow = 1
                break
        # refresh Click
        try:
            click = Click.objects.get(fund_id=fund_id, user_id=openid)
            new_click = click.click_count + 1
            click.click_count = new_click
            click.save()
        except:
            new_click = 1
            click = Click(fund_id=fund_id, user_id=openid, click_count=1)
            click.save()
        # refresh score
        new_score = click2score(new_click)
        refresh_score(openid, fund_id, new_score)
        print("个性推荐记录完成", time.time())
    fund = Fund.objects.get(fund_id=fund_id)

    # 基金持仓 基金占比
    position_list = []
    tmp = get_position_and_rate_by_id(fund_id)
    for item in tmp["position"]:
        d = dict()
        d["code"] = item[0]
        d["name"] = item[1]
        d["zb"] = float(item[2][:-1]) / 100
        position_list.append(d)
    print("持仓获取完成", time.time())
    # 基金占比
    position = dict()
    position["stock"] = tmp["rate"][0][1]
    position["bond"] = tmp["rate"][1][1]
    position["cash"] = tmp["rate"][2][1]
    print("占比获取完成", time.time())
    # 基金规模
    size = dict()
    tmp = get_price_and_scale_by_id(fund_id, 20)
    size["money"] = tmp["scale"][0]
    size["date"] = tmp["scale"][1]
    print("规模获取完成", time.time())
    net_asset_value = []
    vary = tmp["price"]
    now_date = vary[len(vary) - 1][0]
    base_value = float(vary[0][1])

    charts_category = []
    charts_worth = []
    for v in reversed(vary):
        tmp = dict()
        tmp["worth"] = v[1]
        tmp["date"] = v[0]
        tmp["day_growth"] = v[2]
        net_asset_value.append(tmp)
        if len(net_asset_value) == 5:
            break
    for v in vary:
        charts_category.append(v[0])
        charts_worth.append(round((float(v[1]) - base_value) / base_value * 100, 2))
    now_worth = vary[len(vary) - 1][1]
    print("净值获取完成", time.time())
    obj = {
        "fundId": fund.fund_id,
        "fundName": fund.fund_name,
        "manager": fund.manager,
        "dayGrowth": fund.day_growth,
        "yearGrowth": fund.year_growth,
        "category": category2name(fund.category),
        "StockList": position_list,
        "bond": position["bond"],
        "cash": position["cash"],
        "stock": position["stock"],
        "now_date": now_date,
        "fund_size": size["money"],
        "netAssetValue": net_asset_value,
        "now_worth": now_worth,
        "dayIncrease": 1,
        "dayDecrease": 0,
        "yearIncrease": 1,
        "yearDecrease": 0,
        "have_follow": have_follow,
        "charts_worth": charts_worth,
        "charts_category": charts_category
    }
    print("全部完成", time.time())
    return HttpResponse(json.dumps(obj))


def sector(request):
    obj = json.loads(request.body)
    type = obj["type"]
    db = pymysql.connect(host="114.115.160.16", user="root", password="123456Aa!", database="fund")
    cursor = db.cursor()
    all_fund = []
    print("开始",time.time())

    data = []
    funds = []
    now_fund = obj["list"]

    is_recommend = obj["isRecommend"]
    if is_recommend == "0":
        if type == "1":
            sql = "select * from api_fund where category=1"
            cursor.execute(sql)
            all_fund = cursor.fetchall()
            # all_fund = Fund.objects.filter(category=1)
        elif type == "2":
            sql = "select * from api_fund where category=2"
            cursor.execute(sql)
            all_fund = cursor.fetchall()
            # all_fund = Fund.objects.filter(category=2)
        elif type == "3":
            sql = "select * from api_fund where category=3"
            cursor.execute(sql)
            all_fund = cursor.fetchall()
            # all_fund = Fund.objects.filter(category=3)
        elif type == "4":
            sql = "select * from api_fund where category=4"
            cursor.execute(sql)
            all_fund = cursor.fetchall()
            # all_fund = Fund.objects.filter(category=4)
        elif type == "5":
            sql = "select * from api_fund where category=5"
            cursor.execute(sql)
            all_fund = cursor.fetchall()
            # all_fund = Fund.objects.filter(category=5)
        print("选择完成", time.time())
        for i in range(20):
            tmp = random.choice(all_fund)[0]
            while tmp in now_fund:
                tmp = random.choice(all_fund)[0]
            now_fund.append(tmp)
            funds.append(tmp)
        print("随机筛选完成",time.time())
    if is_recommend == '1':
        # score(20)
        user_id = get_openid(obj['userCode'])
        # all_score = UserFundScore.objects.filter(user_id=user_id)
        # sql = "select * from api_userfundscore where user_id='%s'" % (user_id)
        sql = "select * from api_userfundscore where user_id='%s' and fund_id in (select fund_id from api_fund where category=%s)" % (user_id, type)
        db = pymysql.connect(host="114.115.160.16", user="root", password="123456Aa!", database="fund")
        cursor = db.cursor()
        cursor.execute(sql)
        all_score = cursor.fetchall()
        tmp = []
        for score in all_score:
            tmp.append((score[2], score[4]))
        all_score = sorted(tmp, key=lambda sr: sr[1], reverse=True)
        cnt = 0
        for score in all_score:
            if score[0] not in now_fund:
                now_fund.append(score[0])
                funds.append(score[0])
                cnt += 1
            if cnt >= 20:
                break
        print("筛选完成",time.time())

    for fund_id in funds:
        #fund = Fund.objects.get(fund_id=fund_id)
        sql = "select * from api_fund where fund_id='%s'" % (fund_id)
        cursor.execute(sql)
        fund = cursor.fetchone()
        tmp = dict()
        tmp["fundId"] = fund[0]
        tmp["fundName"] = fund[1]
        tmp["dayGrowth"] = fund[7]

        tmp["netAssetValue"] = fund[-1]
        data.append(tmp)
    res = dict()
    res["data"] = data
    print("信息查询完成",time.time())
    return HttpResponse(json.dumps(res))


def follow(request):
    code = request.GET["userCode"]
    op_type = request.GET["type"]
    fund_id = request.GET["fundId"]
    open_id = get_openid(code)
    if op_type == "1":
        follow = Follow(fund_id=fund_id, user_id=open_id)
        refresh_score(open_id, fund_id, 8)
        follow.save()
    else:
        follow = Follow.objects.get(fund_id=fund_id, user_id=open_id)
        follow.delete()
        user_fund_score = UserFundScore.objects.get(fund_id=fund_id, user_id=open_id)
        user_fund_score.is_operated = 0
        user_fund_score.score = 0
        user_fund_score.save()
    res = dict()
    res["isSuccess"] = 1
    return HttpResponse(json.dumps(res))


def bill(request):
    user_id = get_openid(request.GET["userCode"])
    show_num = request.GET["show_num"]
    checks = Check.objects.filter(user_id=user_id)
    bill = []
    tmp_check = []
    for check in reversed(checks):
        tmp_check.append(check)
    checks = tmp_check
    for check in checks[int(show_num):int(show_num) + 10]:
        tmp = dict()
        tmp["time"] = check.time.strftime("%Y-%m-%d %H:%M:%S")
        if check.category == 0:
            tmp["type"] = "买入"
            tmp["money"] = check.money
        elif check.category == 1:
            tmp["type"] = "卖出"
            if check.complete == 0:
                tmp["money"] = check.number
            else:
                tmp["money"] = check.money
        else:
            tmp["type"] = "定投"
            tmp["money"] = check.money
        tmp["fund_name"] = Fund.objects.get(fund_id=check.fund_id).fund_name
        if check.complete == 1:
            tmp["status"] = "已完成"
        elif check.complete == 0:
            tmp["status"] = "正在处理"
        tmp["success"] = check.complete
        bill.append(tmp)

    res = dict()
    res["bill"] = bill
    return HttpResponse(json.dumps(res))


def follow_list(request):
    user_id = get_openid(request.GET["userCode"])
    show_num = request.GET["show_num"]
    follows = Follow.objects.filter(user_id=user_id)
    res = dict()
    data = []
    for follow in follows[int(show_num):int(show_num) + 10]:
        tmp = dict()
        fund = Fund.objects.get(fund_id=follow.fund_id)
        tmp["fundId"] = fund.fund_id
        tmp["name"] = fund.fund_name
        tmp["day_growth"] = fund.day_growth
        holds = Hold.objects.filter(user_id=user_id, fund_id=fund.fund_id)
        tmp["netValue"] = fund.price
        if len(holds) == 0:
            tmp["have"] = 0
        else:
            tmp["have"] = 1
        data.append(tmp)
    res["data"] = data
    return HttpResponse(json.dumps(res))


def buy(request):
    fund_id = request.GET["fundId"]
    user_id = get_openid(request.GET["userCode"])
    amount = request.GET["amount"]
    user = User.objects.get(openid=user_id)
    refresh_score(user_id, fund_id, 10)
    res = dict()
    if user.money >= float(amount):
        res["isSuccess"] = 0
        now = datetime.now().__format__("%Y-%m-%d %H:%M:%S")
        queue = Queue(user_id=user_id, fund_id=fund_id, category=0, money=float(amount), number=0, time=now)
        queue.save()
        user.money -= float(amount)
        user.save()
        check = Check(buy_time=now,user_id=user_id, fund_id=fund_id, number=0, money=amount, time=now, category=0, complete=0)
        check.save()
    else:
        res["isSuccess"] = 1
    return HttpResponse(json.dumps(res))


def sell(request):
    fund_id = request.GET["fundId"]
    user_id = get_openid(request.GET["userCode"])
    shares = request.GET["shares"]
    res = dict()
    hold = Hold.objects.filter(user_id=user_id, fund_id=fund_id)
    if len(hold) == 0:
        res["isSuccess"] = 2
        return HttpResponse(json.dumps(res))
    hold = hold[0]
    if hold.number >= float(shares):
        res["isSuccess"] = 0
        now = datetime.now().__format__("%Y-%m-%d %H:%M:%S")
        if hold.number - float(shares) <= 0.1:
            queue = Queue(user_id=user_id, fund_id=fund_id, category=1, money=0, number=hold.number, time=now)
            queue.save()
            hold.delete()
            check = Check(buy_time=now,user_id=user_id, fund_id=fund_id, number=hold.number, money=0, time=now, category=1, complete=0)
            check.save()
        else:
            queue = Queue(user_id=user_id, fund_id=fund_id, category=1, money=0, number=float(shares), time=now)
            queue.save()
            hold.cost = hold.cost - hold.cost * (float(shares) / hold.number)
            hold.save()
            hold.number -= float(shares)
            hold.save()
            check = Check(buy_time=now,user_id=user_id, fund_id=fund_id, number=float(shares), money=0, time=now, category=1, complete=0)
            check.save()
    else:
        res["isSuccess"] = 1
    return HttpResponse(json.dumps(res))


def timing(request):
    fund_id = request.GET["fundId"]
    user_id = get_openid(request.GET["userCode"])
    amount = request.GET["amount"]
    span = request.GET["span"]
    date = request.GET["date"]
    number = 1
    if span == "1":
        number = 0
    refresh_score(user_id, fund_id, 10)
    timing = Timing(fund_id=fund_id, user_id=user_id, money=float(amount),
                    span=span, date=date, number=number)

    timing.save()
    res = dict()
    res["isSuccess"] = 1
    return HttpResponse(json.dumps(res))


def transc(request):
    fund_id = request.GET["fundId"]
    openid = get_openid(request.GET["userCode"])
    fund = Fund.objects.get(fund_id=fund_id)
    res = dict()
    res["buySourceRate"] = fund.buy_source_rate
    res["buyMin"] = fund.buy_min
    res["buyRate"] = fund.buy_rate
    res["netAssetValue"] = get_price_by_id(fund_id)
    hold = Hold.objects.filter(user_id=openid,fund_id=fund_id)
    if len(hold) == 0:
        res["haveShares"] = 0
    else:
        res["haveShares"] = hold[0].number
    return HttpResponse(json.dumps(res))


def purchased(request):
    openid = get_openid(request.GET["userCode"])
    show_num = request.GET["show_num"]
    data = []
    holds = Hold.objects.filter(user_id=openid)
    earn_have = 0   # 持有收益
    sum = 0
    money_sum = 0
    for hold in holds[int(show_num):int(show_num) + 10]:
        tmp = dict()
        tmp["fundId"] = hold.fund_id
        fund = Fund.objects.get(fund_id=hold.fund_id)
        tmp["name"] = fund.fund_name
        tmp["day_growth"] = fund.day_growth
        value = get_price_by_id(fund.fund_id)
        tmp["netValue"] = value
        tmp["value"] = value * hold.number    # 金额
        tmp["earn"] = tmp["value"] - hold.cost  # 收益
        tmp["earnRate"] = tmp["earn"] / hold.cost   # 收益率
        earn_have += tmp["earn"]  # 持有收益
        sum += tmp["value"]
        money_sum += tmp["value"]
        data.append(tmp)


    ###
    xxx = 0
    queues = Check.objects.filter(user_id=openid)
    for queue in queues:
        if queue.complete == 0:
            xxx += queue.money

    res = dict()
    res["data"] = data
    earn_sum = sum + User.objects.get(openid=openid).money - 10000
    res["earnSum"] = earn_sum + xxx    # 累计收益
    res["earnHave"] = earn_have  # 持有收益
    res["moneySum"] = money_sum # 总金额
    return HttpResponse(json.dumps(res))


def search(request):
    search_info = request.GET["searchInfo"]
    if ord('0') <= ord(search_info[0]) <= ord('9'):  # 数字
        if len(search_info) < 6:
            tmp = "0" * (6 - len(search_info))
            search_info = tmp + search_info
        funds = dict()
        for fund in Fund.objects.all():
            funds[fund.fund_id] = 0
            cnt = 0
            for char in fund.fund_id:
                if cnt >= len(search_info):
                    break
                if char == search_info[cnt]:
                    cnt += 1
            funds[fund.fund_id] += cnt
        cnt = 0
        funds_id = []
        for i in reversed(sorted(funds.items(), key = lambda kv:(kv[1], kv[0]))):
            funds_id.append(i[0])
            cnt += 1
            if cnt == 10:
                break
        data = []
        for fund_id in funds_id:
            fund = Fund.objects.get(fund_id=fund_id)
            tmp = dict()
            tmp["fundId"] = fund.fund_id
            tmp["name"] = fund.fund_name
            tmp["increase"] = fund.day_growth
            tmp["value"] = 1 #get_price_by_id(fund_id)
            data.append(tmp)
        return HttpResponse(json.dumps({"data": data}))
    else:   # 字母 / 汉字
        funds = dict()
        for fund in Fund.objects.all():
            funds[fund.fund_name] = 0
            cnt = 0
            for char in fund.fund_name:
                if cnt >= len(search_info):
                    break
                if char == search_info[cnt]:
                    cnt += 1
            funds[fund.fund_name] += cnt
        cnt = 0
        funds_name = []
        for i in reversed(sorted(funds.items(), key=lambda kv: (kv[1], kv[0]))):
            funds_name.append(i[0])
            cnt += 1
            if cnt == 10:
                break
        data = []
        for fund_name in funds_name:
            fund = Fund.objects.get(fund_name=fund_name)
            tmp = dict()
            tmp["fundId"] = fund.fund_id
            tmp["name"] = fund.fund_name
            tmp["increase"] = fund.day_growth
            tmp["value"] = 1 #get_price_by_id(fund.fund_id)
            data.append(tmp)
        return HttpResponse(json.dumps({"data": data}))


def reset(request):
    openid = get_openid(request.GET["userCode"])
    for check in Check.objects.filter(user_id=openid):
        check.delete()
    for hold in Hold.objects.filter(user_id=openid):
        hold.delete()
    for queue in Queue.objects.filter(user_id=openid):
        queue.delete()
    for timing in Timing.objects.filter(user_id=openid):
        timing.delete()
    for remind in Remind.objects.filter(user_id=openid):
        remind.delete()

    user = User.objects.get(openid=openid)
    user.money = 10000
    user.save()
    return HttpResponse(json.dumps({"isSuccess": 1}))


def preference(request):
    openid = get_openid(request.GET["userCode"])
    #openid = request.GET["userCode"]
    type = request.GET["type"]
    out_scale = []
    out_term = []
    out_userType = []
    if type in ["0", "1"]:
        scales = eval(request.GET["scale"])
        terms = eval(request.GET["term"])
        userTypes = eval(request.GET["userType"])
        in_data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        for scale in scales:
            in_data[int(scale)-1] = 1
        for term in terms:
            in_data[int(term)+3] = 1
        for userType in userTypes:
            in_data[int(userType)+7] = 1
        preference = Preference.objects.get(user_id=openid)
        preference.scale1 = in_data[0]
        preference.scale2 = in_data[1]
        preference.scale3 = in_data[2]
        preference.scale4 = in_data[3]
        preference.term1 = in_data[4]
        preference.term2 = in_data[5]
        preference.term3 = in_data[6]
        preference.term4 = in_data[7]
        preference.stable = in_data[8]
        preference.balance = in_data[9]
        preference.advance = in_data[10]
        preference.save()
        preference_vector = PreferenceVector.objects.get(user_id=openid)
        preference2vector(in_data, preference_vector)
        preference_vector.save()
        user = User.objects.get(openid=openid)
        user.instruction = 1
        user.save()
    elif type == "2":
        preference = Preference.objects.get(user_id=openid)
        if preference.scale1:
            out_scale.append('1')
        if preference.scale2:
            out_scale.append('2')
        if preference.scale3:
            out_scale.append('3')
        if preference.scale4:
            out_scale.append('4')
        if preference.term1:
            out_term.append('1')
        if preference.term2:
            out_term.append('2')
        if preference.term3:
            out_term.append('3')
        if preference.term4:
            out_term.append('4')
        if preference.stable:
            out_userType.append('1')
        if preference.balance:
            out_userType.append('2')
        if preference.advance:
            out_userType.append('3')
    res = dict()
    res["scale"] = out_scale
    res["term"] = out_term
    res["userType"] = out_userType
    res["isSuccess"] = 1
    return HttpResponse(json.dumps(res))


def aipList(request):
    openid = get_openid(request.GET["userCode"])
    timings = Timing.objects.filter(user_id=openid)
    aip_list = []
    for timing in timings:
        tmp = dict()
        fund = Fund.objects.get(fund_id=timing.fund_id)
        tmp["fundName"] = fund.fund_name
        tmp["aipMoney"] = timing.money
        if timing.span == 0:
            if timing.date == 0:
                tmp["date"] = "每周周一"
            elif timing.date == 1:
                tmp["date"] = "每周周二"
            elif timing.date == 2:
                tmp["date"] = "每周周三"
            elif timing.date == 3:
                tmp["date"] = "每周周四"
            else:
                tmp["date"] = "每周周五"
        elif timing.span == 1:
            if timing.date == 0:
                tmp["date"] = "每两周周一"
            elif timing.date == 1:
                tmp["date"] = "每两周周二"
            elif timing.date == 2:
                tmp["date"] = "每两周周三"
            elif timing.date == 3:
                tmp["date"] = "每两周周四"
            else:
                tmp["date"] = "每两周周五"
        elif timing.span == 2:
            tmp["date"] = "每月" + str(timing.date + 1) + "日"
        else:
            tmp["date"] = "每日"
        tmp["aipId"] = timing.id
        aip_list.append(tmp)
    res = dict()
    res["aipList"] = aip_list
    return HttpResponse(json.dumps(res))


def cancelAip(request):
    aip_id = request.GET["aipId"]
    timing = Timing.objects.get(pk=aip_id)
    timing.delete()
    res = {
        "isSuccess": 1
    }
    return HttpResponse(json.dumps(res))


## 新加 讨论区有关功能
def get_fund_discussion(request):
    fund_id = request.GET["fundId"]
    discussion_list = []
    discussions = Discussion.objects.filter(fund_id=fund_id)
    user_id = "null"
    if request.GET["userCode"] != "null":
        user_id = get_openid(request.GET["userCode"])
    for discussion in reversed(discussions):
        tmp = dict()
        user = User.objects.get(openid=discussion.user_id)
        tmp["userImage"] = user.image_url
        tmp["userName"] = user.username
        tmp["info"] = discussion.text
        tmp["time"] = discussion.time.strftime("%Y-%m-%d %H:%M:%S")
        tmp["thumbs"] = len(DiscussionThumb.objects.filter(discussion=discussion))
        tmp["dissId"] = discussion.id
        tmp["reply"] = len(Reply.objects.filter(discussion=discussion))
        if request.GET["userCode"] == "null":
            tmp["canDelete"] = 0
            tmp["liked"] = 0
        else:
            if discussion.user_id == user_id:
                tmp["canDelete"] = 1
            else:
                tmp["canDelete"] = 0
            if len(DiscussionThumb.objects.filter(user_id=user_id, discussion=discussion)) == 0:
                tmp["liked"] = 0
            else:
                tmp["liked"] = 1
        discussion_list.append(tmp)
    return HttpResponse(json.dumps({"dissList": discussion_list}))



def deal_discussion(request):
    fund_id = request.GET["fundId"]
    type = request.GET["type"]
    user_id = get_openid(request.GET["userCode"])
    if type == "1":
        text = request.GET["info"]
        now = datetime.now().__format__("%Y-%m-%d %H:%M:%S")
        discussion = Discussion(user_id=user_id, fund_id=fund_id, text=text, time=now)
        discussion.save()
        return HttpResponse(json.dumps({"isSuccess": 1}))
    elif type == "2":
        discussion_id = int(request.GET["dissId"])
        discussion = Discussion.objects.get(pk=discussion_id)
        discussion.delete()
        return HttpResponse(json.dumps({"isSuccess": 1}))
    else:
        reply_id = int(request.GET["replyId"])
        reply = Reply.objects.get(pk=reply_id)
        reply.delete()
        return HttpResponse(json.dumps({"isSuccess": 1}))


def reply_discussion(request):
    fund_id = request.GET["fundId"]
    user_id = get_openid(request.GET["userCode"])
    discussion_id = request.GET["dissId"]
    info = request.GET["replyInfo"]
    discussion = Discussion.objects.get(pk=discussion_id)
    now = datetime.now().__format__("%Y-%m-%d %H:%M:%S")
    reply = Reply(user_id=user_id, discussion=discussion, text=info, time=now)
    reply.save()
    return HttpResponse(json.dumps({"isSuccess": 1}))


def thumb_discussion(request):
    type = request.GET["type"]
    user_id = get_openid(request.GET["userCode"])
    if type == "0": # 点赞或取消点赞评论
        discussion_id = request.GET["dissId"]
        discussion = Discussion.objects.get(pk=discussion_id)
        if len(DiscussionThumb.objects.filter(user_id=user_id, discussion=discussion)) == 0:
            discussion_thumb = DiscussionThumb(user_id=user_id, discussion=discussion)
            discussion_thumb.save()
        else:
            discussion_thumb = DiscussionThumb.objects.get(user_id=user_id, discussion=discussion)
            discussion_thumb.delete()
    elif type == "1":   # 点赞或取消点赞回复
        reply_id = request.GET["replyId"]
        reply = Reply.objects.get(pk=reply_id)
        if len(ReplyThumb.objects.filter(user_id=user_id, reply=reply)) == 0:
            reply_thumb = ReplyThumb(user_id=user_id, reply=reply)
            reply_thumb.save()
        else:
            reply_thumb = ReplyThumb.objects.get(user_id=user_id, reply=reply)
            reply_thumb.delete()
    return HttpResponse(json.dumps({"isSuccess": 1}))


def get_discussion_detail(request):
    discussion_id = request.GET["dissId"]
    discussion = Discussion.objects.get(pk=discussion_id)
    reply_list = []
    replies = Reply.objects.filter(discussion=discussion)
    user_id = "null"
    if request.GET["userCode"] != "null":
        user_id = get_openid(request.GET["userCode"])
    for reply in reversed(replies):
        tmp = dict()
        tmp["replyInfo"] = reply.text
        tmp["thumbs"] = len(ReplyThumb.objects.filter(reply=reply))
        tmp["userImage"] = User.objects.get(openid=reply.user_id).image_url
        tmp["userName"] = User.objects.get(openid=reply.user_id).username
        tmp["time"] = reply.time.strftime("%Y-%m-%d %H:%M:%S")
        tmp["replyId"] = reply.id
        if request.GET["userCode"] == "null":
            tmp["canDelete"] = 0
            tmp["liked"] = 0
        else:
            if reply.user_id == user_id:
                tmp["canDelete"] = 1
            else:
                tmp["canDelete"] = 0
            if len(ReplyThumb.objects.filter(user_id=user_id, reply=reply)) == 0:
                tmp["liked"] = 0
            else:
                tmp["liked"] = 1
        reply_list.append(tmp)
    return HttpResponse(json.dumps({"replyList": reply_list}))


def get_remind(request):
    user_id = get_openid(request.GET["userCode"])
    res = dict()
    res["haveFirst"] = len(Remind.objects.filter(user_id=user_id, see=0, type=1))
    res["haveSecond"] = len(Remind.objects.filter(user_id=user_id, see=0, type=2))
    res["haveThird"] = len(Remind.objects.filter(user_id=user_id, see=0, type=3))
    return HttpResponse(json.dumps(res))


def get_remind_info(request):
    user_id = get_openid(request.GET["userCode"])
    type = request.GET["type"]
    remind_list = []
    reminds = Remind.objects.filter(user_id=user_id, type=type)
    for remind in reversed(reminds):
        remind.see = 1
        remind.save()
        tmp = dict()
        tmp["Info"] = remind.information
        tmp["Time"] = remind.time.strftime("%Y-%m-%d %H:%M:%S")
        tmp["fundId"] = remind.fund_id
        remind_list.append(tmp)
    return HttpResponse(json.dumps({"remindList": remind_list}))


def get_openid(code):
    if code == "test":
        return "test_openid"
    appid = 'wxdb9ce4f3781d5dac'
    secret = 'd04e971aab99028784e4bb66d1210786'
    url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code'
    response = urllib.request.urlopen(url).read().decode("UTF-8")
    user = json.loads(response)
    openid = user["openid"]
    return openid


def refresh_score(user_id, fund_id, new_score):
    try:
        user_fund_score = UserFundScore.objects.get(user_id=user_id, fund_id=fund_id)
        if user_fund_score.is_operated == 0:
            user_fund_score.is_operated = 1
            user_fund_score.score = new_score
            user_fund_score.save()
        elif new_score > user_fund_score.score:
            user_fund_score.score = new_score
            user_fund_score.save()
    except:
        pass


def click2score(click):
    if 1 <= click <= 39:
        return 3
    if 40 <= click <= 49:
        return 4
    if 50 <= click <= 59:
        return 5
    if 60 <= click:
        return 6
    return 0

def preference2vector(in_data, preference_vector):
    clears = ["day4", "week4", "month4", "three_month4", "six_month4", "year4",
             "stock1", "stock2", "stock3", "stock4", "bond3", "bond4", "scale1", "scale2", "scale3", "scale4"]
    for clear in clears:
        exec("preference_vector.{} = 0".format(clear))
    fills = [["scale1"], ["scale2"], ["scale3"], ["scale4"], ["day4", "week4", "month4", "three_month4"],
             ["three_month4", "six_month4"], ["six_month4", "year4"], ["year4"],
             ["stock1", "bond4"], ["stock2", "bond3"], ["stock3", "stock4"]]
    for i in range(11):
        if in_data[i] == 1:
            for fill in fills[i]:
                exec("preference_vector.{} = 1".format(fill))
    norm_groups = ["day", "week", "month", "three_month", "six_month", "year", "stock", "bond", "cash", "scale"]
    for norm_group in norm_groups:
        exec("tmp_sum = 0.00001")
        for i in range(1, 5):
            exec("tmp_sum += preference_vector.{}{}".format(norm_group, i))
        for i in range(1, 5):
            exec("preference_vector.{}{} /= tmp_sum".format(norm_group, i))
    exec("tmp_sum = 0.00001")
    for i in range(1, 6):
        exec("tmp_sum += preference_vector.type{}".format(i))
    for i in range(1, 6):
        exec("preference_vector.type{} /= tmp_sum".format(i))


def category2name(category):
    names = ["", "股票型", "混合型", "债券型", "指数型", "货币型"]
    return names[category]
